/**
 * 
 */
package com.kylin.erp.oa.system.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.spring.Inject;
import com.jfinal.plugin.spring.IocInterceptor;
import com.kylin.erp.dbmodel.TDepts;
import com.kylin.erp.oa.system.service.SystemOrgnService;
import com.kylin.frame.core.BaseController;
import com.kylin.frame.util.encrypt.TripleDes;

/**
 * @author huxiang
 * 
 */
@Before(IocInterceptor.class)
public class OrgnController extends BaseController {

	@Inject.BY_TYPE
	private SystemOrgnService systemOrgnService;

	public void index() {

		this.setAttr("treenodes", systemOrgnService.getUserOrgns("kylin", 0));
		this.render("index.html");
	}

	public void query() {

		if (StringUtils.isEmpty(getPara("id"))) {
			this.renderJson(TDepts.dao.paginateDataTables(getParaToInt("page")
					.intValue(), getParaToInt("rp").intValue(),
					"select id_,name_,desc_,admin_username_",
					"from t_depts where company_id_ = 'kylin'"));
		} else {
			this.renderJson(TDepts.dao.paginateDataTables(getParaToInt("page")
					.intValue(), getParaToInt("rp").intValue(),
					"select id_,name_,desc_,admin_username_",
					"from t_depts where parent_id_ = ?", getPara("id")));
		}
	}

	public void tree() {

		this.renderJson(systemOrgnService.getUserOrgns("kylin", 0).toString());
	}

	@Before(Tx.class)
	public void add() {

		Map<String, Object> attrs = new HashMap<String, Object>();
		attrs.put("name_", this.getPara("name_"));
		attrs.put("desc_", this.getPara("desc_"));
		attrs.put("admin_username_", this.getPara("admin_username_"));
		attrs.put("company_id_", "kylin");
		attrs.put("parent_id_", StringUtils.isEmpty(getPara("pId")) ? "0"
				: getPara("pId"));
		new TDepts().setAttrs(attrs).save();
		this.renderJson("msg", "添加成功");
	}

	public void get() {

		setAttr("orgn", TDepts.dao.findById(this.getPara("id"))).render(
				"modifyOrgn.html");
	}

	@Before(Tx.class)
	public void modify() {

		Map<String, Object> attrs = new HashMap<String, Object>();
		attrs.put("name_", this.getPara("name_"));
		attrs.put("desc_", this.getPara("desc_"));
		TDepts.dao.findById(this.getPara("id")).setAttrs(attrs).update();
		this.renderJson("msg", "修改成功");
	}
	
	@Before(Tx.class)
	public void del() {
		String[] ids = this.getPara("ids").split(",");
		for (String id : ids) {
			new TDepts().deleteById(id);
		}
		this.renderJson("msg", "删除成功");
	}

	public static void main(String[] a) {
		System.out.println(TripleDes.encrypt("superadmin", null));
	}
}
